package com.jf3q.front.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.domain.EduTeacher;
import com.jf3q.common.mapper.EduTeacherMapper;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.utils.SaltPassUtils;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.dto.MemberLoginDto;
import com.jf3q.front.dto.MemberRegDto;
import com.jf3q.front.service.MemberService;
import com.jf3q.front.system.Constant;
import com.jf3q.front.vo.LoginSuccessVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/member")
@Tag(name = "会员控制层")
public class MemberController {
    @Value("${ali.endpoint}")
    private String endpoint;
    @Value("${ali.endpoint2}")
    private String endpoint2;
    @Value("${ali.bucketName}")
    private String bucketName;
    @Value("${ali.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.accessKeySecret}")
    private String secretAccessKey;


    @Autowired
    MemberService memberService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @PostMapping("/reg")
    @Operation(summary = "会员注册")
    public ResultVo reg(@RequestBody MemberRegDto memberRegDto){

        //校验各种
        memberService.reg(memberRegDto);
        return ResultVo.success();

    }


    @PostMapping("/login")
    @Operation(summary = "会员登陆")
    public ResultVo login(@RequestBody MemberLoginDto memberLoginDto){

        //.trim()把空格去掉
        if (StringUtils.isEmpty(memberLoginDto.getMobile().trim())) {
            return ResultVo.error("手机号必填");
        }else if (StringUtils.isEmpty(memberLoginDto.getPassword())) {
            return ResultVo.error("密码必填");
        }else{
            LambdaQueryWrapper<EduMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EduMember::getMobile, memberLoginDto.getMobile());
            EduMember member = memberService.getOne(queryWrapper);
            if(ObjectUtils.isEmpty(member)){
                return ResultVo.error("账号不存在");
            }
            if(member.getIsDisabled()){
                return ResultVo.error("账号已被禁用");
            }

            //校验密码是否正确（这里做了加盐加密）
            if (!SaltPassUtils.PasswordValidation(member.getSalt(),memberLoginDto.getPassword(),member.getPassword())) {
                return ResultVo.error("密码错误");
            }

            //生成token返回给前端
            String token = jwtTokenUtil.getToken(member.getMobile());

            //把token和个人基本信息返回给前端
            //把敏感信息置空
            member.setPassword(null);
            member.setSalt(null);
            return ResultVo.success( new LoginSuccessVo(token,member));

        }


    }


    @GetMapping("/profile/getMemberInfo/{id}")
    @Operation(summary = "个人信息")
    public ResultVo getMember(@PathVariable String id){
        EduMember byId = memberService.getById(id);
        return ResultVo.success("个人信息",byId);
    }


    @PostMapping("/uploadAva/{type}")
    @Operation(summary = "上传头像")
    public ResultVo UploadAva(@RequestParam("file") MultipartFile file,@PathVariable String type){
        if (file==null || file.isEmpty()){
            return ResultVo.error("文件必填");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd");
        String dataPath = format.format(new Date());
        String fileName=dataPath+"/"+ UUID.randomUUID().toString().replace("-","")+suffix;
        StringBuffer objectName = new StringBuffer();
        switch (type){
            case Constant.UploadType.AVATAR:
            case Constant.UploadType.VIDEO:
            case Constant.UploadType.COVER:
                objectName.append(type).append("/");
                break;
            default:
                return ResultVo.error("参数错误");
        }
        objectName.append(fileName);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,secretAccessKey);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName.toString(), file.getInputStream());

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            String url="https://"+bucketName+"."+endpoint2+"/"+objectName;

            System.out.println(url);

            //拿到最终上传成功的url
            return ResultVo.success("",url);
        } catch (Exception e) {
            return ResultVo.error("上传阿里云失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @PostMapping("/profile/upMember")
    @Operation(summary = "修改个人信息+修改头像")
    public ResultVo UpMenber(EduMember member){
        boolean b = memberService.updateById(member);
        return ResultVo.success("个人信息",b);

    }


}
